package main

import (
	"fmt"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"strconv"
	"time"
)

func main() {
	http.HandleFunc("/ws", handleWebSocket)
	log.Fatal(http.ListenAndServe(":9090", nil))
}

func handleWebSocket(writer http.ResponseWriter, request *http.Request) {
	w := &websocket.Upgrader{}
	upgrade, err := w.Upgrade(writer, request, nil)
	if err != nil {
		fmt.Printf("cannot Upgrade err:%v", err)
	}

	defer upgrade.Close()
	done := make(chan struct{})

	go func() {
		for {
			m := make(map[string]interface{})
			err := upgrade.ReadJSON(&m)
			if err != nil {
				if !websocket.IsCloseError(err,
					websocket.CloseGoingAway,
					websocket.CloseNormalClosure) {
					fmt.Printf("ReadJSON %v\n", err)
				}
				done <- struct{}{}
				break
			}

			fmt.Printf("message received:%v\n", m)
		}

	}()

	i := 0
	for {

		select {
		case <-time.After(200 * time.Millisecond):
		case <-done:
			return
		}
		i++
		err := upgrade.WriteJSON(map[string]string{
			"hello":  "websocket",
			"msg_id": strconv.Itoa(i),
		})

		if err != nil {
			fmt.Printf("WriteJSON %v\n", err)
		}

	}

}
